/**
 * 
 */
package com.wissen.giskard.server;



import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
/**
 * @author Swapnil Sonawane
 *
 * @created date :06-Aug-2010
 */
public class HibernateUtil {

   private final Logger logger =Logger.getLogger(HibernateUtil.class);
   
   private Session session;
   
   private Transaction transaction;
   
   private static final SessionFactory sessionFactory;
   
   static{
	   try
	   {
		   sessionFactory=new AnnotationConfiguration().configure().buildSessionFactory();
	   }
	   catch (Throwable  ex) {
		   System.err.println("Initial SessionFactory creation failed." + ex);
           throw new ExceptionInInitializerError(ex);
	   }
   }
   
   public HibernateUtil()
   {
	   session=sessionFactory.openSession();
	   transaction=session.beginTransaction();
   }
	
   
  
   
   public void commit()
   {
	   try{
		   if(transaction.isActive()){
			   transaction.commit();
		   }
	   }
	   catch (Throwable e) {
		logger.fatal("Exception ..",e);
	   }
	   closeSession();
   }

  
   
   public void rollback()
   {
	   try{
		   if(transaction.isActive()){
			   transaction.rollback();
		   }
	   }
	   catch (Throwable e) {
		logger.fatal("Exception ..",e);
	   }
	   closeSession();
   }

  
   
   private void closeSession() {
		try{
			if(session.isOpen()){
				session.close();
			}
		}
		catch (Throwable e) {
			logger.fatal("Exception ..",e);
		}
	
   }




   public Session getSession() {
	   return session;
   }




	public void setSession(Session session) {
		this.session = session;
	}
	
	
	
	
	public Transaction getTransaction() {
		return transaction;
	}
	
	
	
	
	public void setTransaction(Transaction transaction) {
		this.transaction = transaction;
	}
	
		
}
